<template>
  <div>
    <a-table show-summary :pagination="myPagination" :scroll="{ x: 1500, y: tableHeight }"
             :cell-style="{padding:'0px',cursor: 'pointer'}"
             :rowKey="(record, index) => { return index }"
             :columns="columnBox" :data-source="tableData" size="small" bordered>
      <template slot="HREFCOM" slot-scope="text, record">
        <a-dropdown>
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">
            {{ record.HREFCOM }}
            <a-icon type="down"/>
          </a>
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">
            {{ record.YZMC }}
            <a-icon type="down"/>
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a :href="'http://localhost:8910/#/query/gasStation02list01/query?SHIFTNO='+ record.HREFCOM+'&CKMC='+encodeURI(record.YZMC)+'&KSSJ='+Date.parse(new Date(record.KSSJ))+'&JSSJ='+Date.parse(new Date(record.JSSJ))"
                 target="_blank">加油站交接班记录</a>
            </a-menu-item>
            <a-menu-item>
              <a :href="'http://localhost:8910/#/query/gasStation02list02/query?SHIFTNO='+ record.HREFCOM+'&CKMC='+encodeURI(record.YZMC)+'&KSSJ='+encodeURI(record.KSSJ)+'&JSSJ='+encodeURI(record.JSSJ)"
                 target="_blank">加油站泵码交接记录</a>
            </a-menu-item>
            <a-menu-item>
              <a :href="'http://localhost:8910/#/query/gasStation02list03/query?CKBM='+record.CKBM+'&KSSJ='+encodeURI(record.KSSJ)+'&JSSJ='+encodeURI(record.JSSJ)"
                 target="_blank">加油站机出V20、公斤汇总</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </template>
    </a-table>
  </div>
</template>

<script>
import axios from "axios";
import ExportExcel from "@/assets/js/export";
import _ from "lodash"; // 导出获取表单

export default {
  name: "Table",
  props: {
    projectId: {
      type: String, default: () => {
      }
    },
    queryId: {
      type: String, default: () => {
      }
    },
    conditions: {
      type: Object, default: () => {
      }
    }
  },
  data() {
    return {
      fieldList: {
        type: Array,
        default: () => []
      },
      tableData: [],
      tableHeight: window.innerHeight - 600,
      columnBox: [],
      dataExcel: [], // 导出excel数据
      myPagination: {
        defaultPageSize: 50
      }
    };
  },
  // 监听路由发生变化时刷新信息
  watch: {
    $route(to, from) {
      this.fieldList = [];
      this.tableData = [];
      this.columnBox = [];
      this.loadTableHeader();
    }
  },
  mounted() {
    this.loadTableHeader();
  },
  methods: {
    loadTableHeader() {
      this.tableHeight = window.innerHeight - 600;
      axios
          .get("/api/" +
              this.projectId + "/" + this.queryId + "/getTableFields"
          )
          .then(resp => {
            if (resp.data.code == "500") {
              console.log(resp.data.data);
            } else {
              this.fieldList = resp.data.data;
              const columnBox = resp.data.data;
              for (let i = 0; i < columnBox.length; i++) {
                if (columnBox[i].merge) {
                  columnBox[i].customRender = (text, row, index) => {
                    const obj = {
                      children: text,
                      attrs: {}
                    }
                    const data = this.tableData;
                    obj.attrs.rowSpan = this.getRowSpanCount(data || [], columnBox[i].mergeName, index)
                    return obj
                  }
                }

                if (columnBox[i].dataIndex == 'HREFCOM') {
                  this.$set(columnBox[i], 'scopedSlots', {
                    customRender: 'HREFCOM'
                  });
                  this.$delete(columnBox[i], 'customRender');
                }
              }

              // 合计的另一种方式，后台返回多一条数据
              // columnBox[0].customRender = (text, record, index) => {
              //   if(record.index === '合计'){ return '' } else { return parseInt(index)+1; }
              // }
              this.columnBox = columnBox;
            }
          });
    },
    /*
     * 合并列
     */
    getRowSpanCount(data, key, target) {
      if (!Array.isArray(data)) return 1;
      data = data.map(_ => _[key]); // 只取出筛选项
      let preValue = data[0];
      const res = [[preValue]]; // 放进二维数组里
      let index = 0; // 二维数组下标
      for (let i = 1; i < data.length; i++) {
        if (data[i] === preValue) { // 相同放进二维数组
          res[index].push(data[i]);
        } else { // 不相同二维数组下标+1
          index += 1;
          res[index] = [];
          res[index].push(data[i]);
          preValue = data[i];
        }
      }
      const arr = [];
      res.forEach((_) => {
        const len = _.length;
        for (let i = 0; i < len; i++) {
          arr.push(i === 0 ? len : 0);
        }
      });
      return arr[target];
    },
    loadData(callback) {
      // 特殊字符解码
      if (this.conditions.CKMC) {
        this.conditions.CKMC = decodeURI(this.conditions.CKMC);
      }
      // 如果地址栏参数为KSSJ或JSSJ则转换时间戳格式
      if (this.conditions.KSSJ) {
        this.conditions.KSSJ = this.formatDate(Number(this.conditions.KSSJ));
      }
      if (this.conditions.JSSJ) {
        this.conditions.JSSJ = this.formatDate(Number(this.conditions.JSSJ));
      }
      // 向后台请求数据，并加载查询结果
      this.loadTableHeader();
      this.tableData = [];
      axios
          .post("/api/" +
              this.projectId + "/" + this.queryId + "/execute",
              this.conditions
          )
          .then(resp => {
            callback();
            if (resp.data.code == "500") {
              console.log(resp.data.data);
            } else {
              this.tableData = resp.data.data;
              // 合计写了一半（有问题）
              // this.tableData.push({});
              // for (let i = 0; i < this.sumBox.length; i++) {
              //   console.log(this.sumBox[i].name);
              //   this.tableData[this.tableData.length - 1].AUTO_TYPE = 0;
              //   this.tableData.forEach((item) => {
              //     this.tableData[this.tableData.length - 1].AUTO_TYPE += Number(item.AUTO_TYPE)
              //   })
              //   this.tableData[this.tableData.length - 1].AUTO_TYPE = Number(this.tableData[this.tableData.length - 1].AUTO_TYPE) / 2;
              // }
            }
          });
    },
    // 时间戳转换字符串
    formatDate(value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    },
    dataToExcel() {
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      ExportExcel(this.columnBox, this.dataExcel, y + '' + MM + '' + '' + d + this.$route.query.routerName, this.$route.query.routerName);
    }
  }
};
</script>

<style scoped>
.el-table {
  overflow: visible !important;
}

/deep/ th {
  background-color: #1890FF !important;
  color: #FFFFFF !important;
  font-weight: bold !important;
}
</style>
